package com.lp.guoguo.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Slf4j
public class ExcelUtils {

    /**
     * 导出Excel
     * @param response HTTP响应
     * @param data 数据列表
     * @param fileName 文件名
     * @param sheetName 工作表名
     * @param clazz 实体类
     * @param <T> 泛型
     */
    public static <T> void export(HttpServletResponse response, List<T> data, String fileName,
                                  String sheetName, Class<T> clazz) {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + encodedFileName + ".xlsx");

            EasyExcel.write(response.getOutputStream(), clazz)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet(sheetName)
                    .doWrite(data);
        } catch (IOException e) {
            log.error("Excel导出失败", e);
        }
    }

    /**
     * 读取Excel
     * @param file Excel文件
     * @param clazz 实体类
     * @param <T> 泛型
     * @return 数据列表
     */
    public static <T> List<T> read(MultipartFile file, Class<T> clazz) {
        try {
            return EasyExcel.read(file.getInputStream())
                    .head(clazz)
                    .sheet()
                    .doReadSync();
        } catch (IOException e) {
            log.error("Excel读取失败", e);
            return null;
        }
    }
} 